package com.example.common.task;

import cn.hutool.core.collection.CollectionUtil;
import com.example.common.Constants;
import com.example.common.enums.OrdersStatusEnum;
import com.example.pojo.entity.GoodsOrders;
import com.example.pojo.entity.PetOrders;
import com.example.service.GoodsOrdersService;
import com.example.service.PetOrdersService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单定时任务
 */
@Component
@Slf4j
public class OrdersTask {

    @Resource
    private PetOrdersService petOrdersService;

    @Resource
    private GoodsOrdersService goodsOrdersService;

    /**
     * 每 5 分钟执行一次，自动取消超时未支付的订单
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void handleOrders() {
        log.info("********************************开始执行任务---自动取消超时未支付的订单******************************");
        // 1.查出所有未支付的宠物订单
        List<PetOrders> petOrdersList = this.petOrdersService.lambdaQuery()
                .eq(PetOrders::getStatus, OrdersStatusEnum.CREATED.getName())
                .list();
        // 2.遍历宠物订单，获取超时未支付的宠物订单 id 列表
        List<Integer> petOrdersIdList = new ArrayList<>();
        for (PetOrders petOrders : petOrdersList) {
            // 获取下单时间
            LocalDateTime createOrdersTime = LocalDateTime.parse(petOrders.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 获取当前时间
            LocalDateTime curTime = LocalDateTime.now();
            // 如果下单时间 + 超时时间 <= 当前时间，则订单超时，自动取消订单
            if (!createOrdersTime.plusMinutes(Constants.ORDERS_TIME).isAfter(curTime)) {
                petOrdersIdList.add(petOrders.getId());
            }
        }
        // 3.批量取消宠物订单
        if (CollectionUtil.isNotEmpty(petOrdersIdList)) {
            this.petOrdersService.lambdaUpdate()
                    .in(PetOrders::getId, petOrdersIdList)
                    .set(PetOrders::getStatus, OrdersStatusEnum.CANCEL.getName())
                    .update();
        }
        log.info("********************************成功取消宠物订单的 id 列表：{} ****************************************************************", petOrdersIdList);

        // 4.查出所有未支付的宠物用品订单
        List<GoodsOrders> goodsOrdersList = this.goodsOrdersService.lambdaQuery()
                .eq(GoodsOrders::getStatus, OrdersStatusEnum.CREATED.getName())
                .list();
        // 5.遍历宠物用品订单，获取超时未支付的宠物用品订单 id 列表
        List<Integer> goodsOrdersIdList = new ArrayList<>();
        for (GoodsOrders goodsOrders : goodsOrdersList) {
            // 获取下单时间
            LocalDateTime createOrdersTime = LocalDateTime.parse(goodsOrders.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 获取当前时间
            LocalDateTime curTime = LocalDateTime.now();
            // 如果下单时间 + 超时时间 <= 当前时间，则订单超时，自动取消订单
            if (!createOrdersTime.plusMinutes(Constants.ORDERS_TIME).isAfter(curTime)) {
                goodsOrdersIdList.add(goodsOrders.getId());
            }
        }
        // 6.批量取消宠物用品订单
        if (CollectionUtil.isNotEmpty(goodsOrdersIdList)) {
            this.goodsOrdersService.lambdaUpdate()
                    .in(GoodsOrders::getId, goodsOrdersIdList)
                    .set(GoodsOrders::getStatus, OrdersStatusEnum.CANCEL.getName())
                    .update();
        }
        log.info("********************************成功取消宠物用品订单的 id 列表：{} ****************************************************************", goodsOrdersIdList);
    }
}
